package com.cn.lp.export.server.base.oss;

import com.aliyun.oss.OSSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云OSS
 *
 * @author scofier
 */
@Component
@ConditionalOnClass(OSSClient.class)
public class AliyunOssManager {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKey}")
    private String accessKey;

    @Value("${aliyun.oss.secretKey}")
    private String secretKey;

    @Value("${aliyun.oss.bucketName:test-export}")
    private String bucketName;

    @Value("${aliyun.oss.staticEndPoint:}")
    private String staticEndPoint;

    private OSSClient ossClient;

    @PostConstruct
    public void init() {
        ossClient = new OSSClient(endpoint, accessKey, secretKey);
    }

    /**
     * 上传文件
     * @param objectName 文件名
     * @param content 文件内容
     * @return boolean
     */
    public String putObject(String objectName, byte[] content) {
        this.ossClient.putObject(this.bucketName, objectName, new ByteArrayInputStream(content));
        return this.generateObjectUrl(objectName);
    }

    public String generateObjectUrl(String objectName) {
        return this.staticEndPoint + "/" + objectName;
    }

    @PreDestroy
    public void destruct() {
        ossClient.shutdown();
    }

}
